import React, { Component } from "react"
import { connect } from 'react-redux'
import { AdvancedTable } from "components/index"
import ExportModal from "components/template/export-modal/export-modal"
import { messages, queryCurrencyPrecision } from "share/common"
import { Button, Alert, message } from 'antd'
import NumberRange from "../../financial-management/expense-view/component/number-range"
import moment from 'moment'
import httpFetch from "share/httpFetch"
import FileSaver from 'file-saver'

@connect(mapStateToProps)
class DetailView extends Component{

  state = {
    batchBtnLoading: false,
    searchParams: {},
    searchForm: [
      {
        id: 'companyId', label: messages('finance-4.key20')/*公司*/, component: 'Chooser',
        props: {
          type: 'available_company_setOfBooks',
          labelKey: 'name',
          valueKey: 'id',
          single: true,
          listExtraParams: { enabled: true, setOfBooksId: this.props.company.setOfBooksId }
        },
        initialValue: [{ name: this.props.company.name, id: this.props.company.id }],
        parser: value => ({
          companyId: (value && value.length) ? value[0].id : undefined
        })
      },
      {
        id: 'accountNumber', label: messages('finance-4.key21')/*银行账户*/, component: 'Selector',
        props: {
          selectorItem: {
            url: `/api/companyBankAuth/getAuthCompanyBank/${this.props.loginUser.userOID}`,
            label: item => item.companyBank.bankAccountName,
            key: item => item.companyBank.bankAccountNumber
          },
          entity: true
        },
        parser: value => ({ accountNumber: value ? value.companyBank.bankAccountNumber : undefined })
      },
      {
        id: 'bankName', label: messages('finance-4.key22')/*银行名称*/, component: 'Chooser',
        props: {
          selectorItem: {
            title: messages('finance-4.key23')/*选择银行*/,
            url: `/api/custom/enumerations/template/by/type/page`,
            searchForm: [{
              type: 'input', id: 'keyword', label: messages('finance-4.key22')/*银行名称*/
            }],
            columns: [{
              title: messages('finance-4.key22')/*银行名称*/, dataIndex: 'messageKey'
            }],
            key: 'messageKey'
          },
          valueKey: "messageKey",
          labelKey: "messageKey",
          listExtraParams: { type: '1004' },
          single: true
        },
        parser: value => ({
          bankName: (value && value.length) ? value[0].messageKey : undefined
        })
      },
      { id: 'payeeAccountName', label: messages('finance-4.key24')/*收款方户名*/, components: 'Input' },
      { id: 'payeeAccount', label: messages('finance-4.key25')/*收款方账号*/, components: 'Input' },
      {
        id: 'amount', label: messages('finance-4.key26')/*金额范围*/,
        component: <NumberRange/>,
        parser: value => ({
          amountFrom: value && value[0] ? value[0] : null,
          amountTo: value && value[1] ? value[1] : null
        }),
        tagParser: value => value && (value[0] || value[1]) && `${value[0] === 0 ? value[0] : value[0] || ''} ~ ${value[1] === 0 ? value[1] : value[1] || ''}`
      },
      {
        id: 'tranDate', label: messages('finance-4.key27')/*交易日期范围*/, component: 'DateRangePicker',
        initialValue: [moment(new Date()), moment(new Date())],
        parser: value => ({
          tranDateFrom: value && value[0] ? moment(value[0]).format('YYYY-MM-DD') : null,
          tranDateTo: value && value[1] ? moment(value[1]).format('YYYY-MM-DD') : null
        })
      }
    ],
    loading: false
  };

  columns = [
    { title: messages('finance-4.key22')/*银行名称*/, dataIndex: 'bankName' },
    { title: messages('finance-4.key28')/*银行账号*/, dataIndex: 'accountNumber' },
    { title: messages('finance-4.key29')/*银行户名*/, dataIndex: 'accountName' },
    { title: messages('finance-4.key30')/*交易日期*/, dataIndex: 'tranDate', render: value => value ? moment(value).format('YYYY-MM-DD HH:mm:ss') : '-' },
    { title: messages('finance-4.key31')/*借/贷*/, dataIndex: 'dcFlag' },
    { title: messages('common.amount')/*金额*/, dataIndex: 'amount', render: (value, record) => this.filterMoney(value, queryCurrencyPrecision(record.currencyCode)) },
    { title: messages('common.currency')/*币种*/, dataIndex: 'currency' },
    { title: messages('finance-4.key24')/*收款方户名*/, dataIndex: 'payeeAccountName' },
    { title: messages('finance-4.key32')/*摘要*/, dataIndex: 'remark' },
    { title: messages('finance-4.key33')/*回单编号*/, dataIndex: 'billNo' },
    { title: messages('finance-4.key34')/*批量打印批次号*/, dataIndex: 'bankReceiptBatchNo' },
    { title: messages('finance-4.key35')/*操作人*/, dataIndex: 'oper' },
    { title: messages('finance-4.key36')/*交易流水号*/, dataIndex: 'bankSeqNo', hide: true },
    { title: messages('finance-4.key20')/*公司*/, dataIndex: 'companyName', hide: true },
    { title: messages('finance-4.key37')/*收款人开户行*/, dataIndex: 'payeeBank', hide: true },
    { title: messages('finance-4.key38')/*收款人开户行名*/, dataIndex: 'payeeBankName', hide: true },
    { title: messages('finance-4.key39')/*收款人账号*/, dataIndex: 'payeeAccount', hide: true },
    { title: messages('finance-4.key40')/*用途*/, dataIndex: 'useName', hide: true },
    { title: messages('finance-4.key41')/*余额*/, dataIndex: 'acctBal', hide: true },
    {
      title: messages('common.operation')/*操作*/, dataIndex: 'operator',
      render: (value, record) => record.billNo
        ? <a onClick={e => this.handlePrint(e, record)} disabled={this.props.disabled}>{messages('finance-4.key42')/*打印回单*/}</a>
        : '-'
    }
  ];

  service = (page, size, searchParams) => {
    let temp = {
      ...searchParams,
      tenantId: this.props.tenantInfo.id
    };
    this.setState({ searchParams: temp });
    return httpFetch.post(`/payment/api/receipt/findPage`, Object.assign({
      page, size
    }, temp))
  };

  handlePrint = (e, record) => {
    e.stopPropagation();
    this.setState({ loading: true });
    httpFetch.get(`/payment/api/receipt/printBankReceipt?id=${record.id}`)
      .then(res => {
        window.open(res.data, '_blank')
      })
      .catch(e => {
        message.error(e.response.data.message)
      })
      .finally(() => {
        this.setState({ loading: false });
      })
  };

  toGenerateBatch = () => {
    this.setState({ batchBtnLoading: true });
    const { searchParams } = this.state;
    httpFetch.post(`/payment/api/receipt/buildReceiptBatch`, {...searchParams})
      .then(() => {
        this.props.tabChange('batch-download')
      })
      .catch(e => {
         message.error(e.response.data.message)
      })
      .finally(() => {
        this.setState({ batchBtnLoading: false });
      })
  };

  render() {
    const { batchBtnLoading, searchParams, searchForm, loading } = this.state;
    const { disabled } = this.props;
    return (
      <AdvancedTable
        service={this.service}
        title={messages('finance-4.key1')/*明细查询*/}
        rowKey={'id'}
        tableName='bank-account-view-detail'
        columns={this.columns}
        onRef={ref => this.advancedTableRef = ref}
        searchForm={searchForm}
        propsLoading={loading}
        footer={[
          <ExportModal
            type={"btn"}
            btnType="primary"
            style={{display: 'inline-block', marginRight: '8px'}}
            exportTitle={messages('finance-4.key43')/*导出搜索数据*/}
            exportType="BANK_RECEIPT"
            exportCondition={{
              ...searchParams
            }}
            disabled={disabled}
            exportCommand={'BANK_RECEIPT'}
          />,
          <Button
            loading={batchBtnLoading}
            disabled={disabled}
            onClick={this.toGenerateBatch}
          >
            {messages('finance-4.key44')/*生成回单批次*/}
          </Button>
        ]}
      >
        <Alert
          type="info"
          showIcon
          message={<div
            dangerouslySetInnerHTML={{
              __html: messages('finance-4.key45')/*仅银行电子回单支持范围内的已生效银企直联账户可以在此界面进行回单下载打印；*/ + messages('finance-4.key46')/*列表中<span class='color-blue'>批量打印批次号为空</span>的数据将会生成批次。*/
              /*列表中<span class='color-blue'>批量打印批次号为空</span>的数据将会生成批次。*/
            }}/>}
        />
      </AdvancedTable>
    )
  }

}

function mapStateToProps(state) {
  return {
    company: state.login.company,
    loginUser: state.login.loginUser,
    tenantInfo: state.login.tenant
  }
}

export default DetailView
